package com.cat.orm.core.convert;

import com.cat.orm.core.base.IBasePo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 持久对象转换器
 * @param <D>
 * @param <P>
 */
public interface PersistenceDataConverter<D, P extends IBasePo> {

    public final Logger logger = LoggerFactory.getLogger(PersistenceDataConverter.class);

    /**
     * 获取该bean的唯一主键<br>
     * 对应{@link IBasePo#key()}
     * @return
     */
    Object getKey(D data);

    P data2Po(D data);

    D po2Data(P pojo) throws Exception;

    Class<D> getDataClazz();

    Class<P> getPojoClazz();

    default List<P> dataList2Pos(Collection<D> dataList){
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }
        List<P> newDataList = new ArrayList<>(dataList.size());
        for (D data : dataList) {
            P pojo = this.data2Po(data);
            if (pojo == null) {
                logger.warn("bean[{}] convert data fail.", data);
                continue;
            }
            newDataList.add(pojo);
        }
        return newDataList;
    }

    default List<D> pos2DataList(Collection<P> pos) throws Exception{
        if (pos == null || pos.isEmpty()) {
            return new ArrayList<>();
        }
        List<D> newPojosList = new ArrayList<>(pos.size());
        for (P pojo : pos) {
            D data = po2Data(pojo);
            if (data == null) {
                logger.warn("bean[{}] convert data fail.", data);
                continue;
            }
            newPojosList.add(data);
        }
        return newPojosList;
    }

}
